package com.qdu.bussiness.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import com.qdu.bussiness.constant.BussinessConstant;
import com.qdu.bussiness.domain.*;
import com.qdu.bussiness.service.*;
import com.qdu.common.core.domain.AjaxResult;
import com.qdu.common.utils.SecurityUtils;
import com.qdu.common.utils.id.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qdu.bussiness.mapper.BusRentMapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * 雪具租赁Service业务层处理
 * 
 * @author qdu
 * @date 2022-03-12
 */
@Service
public class BusRentServiceImpl implements IBusRentService 
{
    @Autowired
    private BusRentMapper busRentMapper;

    @Autowired
    private IBusBillService busBillService;

    @Autowired
    private IBusInventoryService busInventoryService;

    @Autowired
    private IBusItemService busItemService;

    @Autowired
    private IBusTicketPurchaseService busTicketPurchaseService;

    /**
     * 查询雪具租赁
     * 
     * @param rentId 雪具租赁主键
     * @return 雪具租赁
     */
    @Override
    public BusRent selectBusRentByRentId(Long rentId)
    {
        return busRentMapper.selectBusRentByRentId(rentId);
    }

    /**
     * 查询雪具租赁列表
     * 
     * @param busRent 雪具租赁
     * @return 雪具租赁
     */
    @Override
    public List<BusRent> selectBusRentList(BusRent busRent)
    {
        if(!SecurityUtils.getUsername().equals("admin")){
            busRent.setRentUserName(SecurityUtils.getUsername());
        }
        return busRentMapper.selectBusRentList(busRent);
    }

    /**
     * 新增雪具租赁
     * 
     * @param busRent 雪具租赁
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insertBusRent(BusRent busRent)
    {
        // 计算开始时间和时间和结束时间的差值
        Date rentStartTime = busRent.getRentStartTime();
        Date rentEndTime = busRent.getRentEndTime();
        if(rentStartTime == null || rentEndTime == null){
            return AjaxResult.error("请选择租赁起止时间！");
        }
        long l = rentEndTime.getTime() - rentStartTime.getTime();
        if(l < 3600000L){
            return AjaxResult.error("租赁时间最少为1小时，请重新选择起止时间！");
        }
        // 查询是否已经拥有账单
        BusBill userTodayBillInfo = busBillService.getUserTodayBillInfo(SecurityUtils.getUsername());
        if(userTodayBillInfo == null || userTodayBillInfo.getBillId() == null){
            return AjaxResult.error("当前用户尚未入园！请先购票！");
        }
        // 检查门票时间与租赁时间关系
        BusTicketPurchase todayTicketPurchase = busTicketPurchaseService.getTodayTicketPurchase();
        if(todayTicketPurchase == null){
            return AjaxResult.error("当前用户尚未验票进园！");
        }
        if(busRent.getRentStartTime().compareTo(todayTicketPurchase.getTicketStartTime()) < 0){
            return AjaxResult.error("租赁开始时间早于购票入园时间！请重新选择时间！");
        }
        if(busRent.getRentEndTime().compareTo(todayTicketPurchase.getTicketEndTime()) > 0){
            return AjaxResult.error("租赁结束时间晚于门票结束时间！请重新选择时间！");
        }
        // 获取当前物料的信息
        BusInventory busInventory = busInventoryService.selectBusInventoryByInventoryId(busRent.getInventoryId());
        // 如果雪具的状态不是空闲，不允许租赁
        if(!BussinessConstant.INVENTORY_STATUS_NORMAL.equals(busInventory.getInventoryStatus())){
            return AjaxResult.error("当前雪具非可租赁状态，请更换其他雪具！");
        }
        // 修改雪具状态
        BusInventory inventoryUpdateDto = new BusInventory();
        inventoryUpdateDto.setInventoryId(busRent.getInventoryId());
        inventoryUpdateDto.setInventoryStatus(BussinessConstant.INVENTORY_STATUS_RENTING);
        int inventoryStatusRes = busInventoryService.updateBusInventory(inventoryUpdateDto);
        if(inventoryStatusRes < 1){
            throw new RuntimeException("修改雪具状态失败！");
        }
        // 查询是否有押金租赁记录
        BusRent queryRent = new BusRent();
        queryRent.setBillId(userTodayBillInfo.getBillId());
        queryRent.setRentType(BussinessConstant.RENT_TYPE_DEPOSIT);
        queryRent.setRentUserName(SecurityUtils.getUsername());
        queryRent.setIsPaid(0L);
        List<BusRent> busRents = busRentMapper.selectBusRentList(queryRent);

        // 没有 -> 新增押金租赁记录
        String result_Bal = "";
        if(busRents.isEmpty()){
            // 查账户余额 有没有200
            String userBalance = busRentMapper.selectUserBalanceByUserName(SecurityUtils.getUsername());
            Double tmp_balance = Double.parseDouble(userBalance);
            // 扣200
            if(tmp_balance < 200){
                throw new RuntimeException("当前账户余额不足200，扣除押金时失败！请充值后再进行租赁！");
            }
            result_Bal = String.valueOf(tmp_balance - 200.00);
            int updBalanceRes = busRentMapper.updateUserBalanceByUserName(SecurityUtils.getUsername(), result_Bal);
            if(updBalanceRes < 1){
                throw new RuntimeException("扣除押金失败！请重试！");
            }
            // 创建押金记录
            BusRent depositRent = new BusRent();
            depositRent.setBillId(userTodayBillInfo.getBillId());
            depositRent.setRentType(BussinessConstant.RENT_TYPE_DEPOSIT);
            depositRent.setRentUserName(SecurityUtils.getUsername());
            // 押金已支付
            depositRent.setIsPaid(1L);
            depositRent.setRentStartTime(busRent.getRentStartTime());
            depositRent.setRentEndTime(busRent.getRentEndTime());
            depositRent.setRentMoney("200.00");
            depositRent.setRentId(IdUtil.getId());
            depositRent.setStatus("new");
            depositRent.setRentQuantity(1L);
            int depositRentRes = busRentMapper.insertBusRent(depositRent);
            if(depositRentRes < 1){
                throw new RuntimeException("创建押金记录失败！");
            }
        }

        // 新增租赁记录
        long total_hours = l / 3600000L;
        // 向上取整
        int ttl_hours = (int)Math.ceil(total_hours);
        // 物料信息
        BusItem busItem = busItemService.selectBusItemById(busInventory.getItemId());
        BigDecimal itemUnitPrice = busItem.getItemUnitPrice();
        busRent.setRentUserName(SecurityUtils.getUsername());
        busRent.setIsPaid(0L);
        busRent.setStatus("new");
        busRent.setBillId(userTodayBillInfo.getBillId());
        busRent.setRentMoney(String.valueOf(itemUnitPrice.multiply(BigDecimal.valueOf(ttl_hours))));
        busRent.setRentId(IdUtil.getId());
        busRent.setRentType(BussinessConstant.RENT_TYPE_ITEM);
        int rentRes = busRentMapper.insertBusRent(busRent);
        if(rentRes < 1){
            throw new RuntimeException("租赁失败！");
        }
        return AjaxResult.success(result_Bal);
    }

    /**
     * 修改雪具租赁
     * 
     * @param busRent 雪具租赁
     * @return 结果
     */
    @Override
    public int updateBusRent(BusRent busRent)
    {
        return busRentMapper.updateBusRent(busRent);
    }

    /**
     * 批量删除雪具租赁
     * 
     * @param rentIds 需要删除的雪具租赁主键
     * @return 结果
     */
    @Override
    public int deleteBusRentByRentIds(Long[] rentIds)
    {
        return busRentMapper.deleteBusRentByRentIds(rentIds);
    }

    /**
     * 删除雪具租赁信息
     * 
     * @param rentId 雪具租赁主键
     * @return 结果
     */
    @Override
    public int deleteBusRentByRentId(Long rentId)
    {
        return busRentMapper.deleteBusRentByRentId(rentId);
    }
}
